<template>
    <div class="edit-box">
        <div class="header">
            <img src="@/assets/img/Address/icon_arrow_left_black.png" alt="" @click="emit('update:isEdit', false)">
            <p v-text="EditModel.id === 0 ? '新增地址' : '编辑地址'"></p>
        </div>
        <div class="container-box">
            <el-form :rules="rules" ref="ruleFormRef" :model="EditModel">
                <el-form-item prop="receiveName" label="收货姓名">
                    <el-input v-model="EditModel.receiveName" />
                </el-form-item>
                <el-form-item prop="receivePhone" label="手机号码">
                    <el-input v-model="EditModel.receivePhone" />
                </el-form-item>
                <el-form-item prop="valueCity" label="收货地区">
                    <el-cascader placeholder="-请选择-  " v-model="valueCity" :props="propsKey" :options="options" />
                </el-form-item>
                <el-form-item prop="receiveDetail" label="详细地址">
                    <el-input v-model="EditModel.receiveDetail" />
                </el-form-item>
                <el-form-item label="设为默认地址">
                    <el-switch v-model="EditModel.isDefault" />
                </el-form-item>
                <p class="remove-edit" @click="remove(EditModel.id)">删除地址</p>
            </el-form>
        </div>
        <div class="footer-eidt">
            <button class="sava-btn" @click="save(ruleFormRef)">保 存</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import City from '@/utils/data'
import { useAddress } from '@/store';
import { ElLoading, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getCurrentInstance } from 'vue';


const { proxy }: any = getCurrentInstance()
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    receiveName: [{ required: true, message: '别忘了写姓名', trigger: 'blur' }],
    receivePhone: [{ required: true, message: '手机号别忘了', trigger: 'blur' }],
    valueCity: [{ required: true, message: '别忘了选', trigger: 'blur' }],
    receiveDetail: [{ required: true, message: '详细地址~', trigger: 'blur' }]

})

interface City {
    code: string;
    name: string;
    province: string;
    city?: string;
    area?: string;
    children?: City[]
}
const Address = useAddress()
//model
const EditModel = ref<HttpPayload.AddressCRUD>({
    id: 0,
    isDefault: 0,
    name: "",
    receiveName: "",
    receiveDetail: "",
    receivePhone: "",
    receiveRegion: ""
})
const valueCity = ref<Array<string>>([])
watch(valueCity, () => {
    EditModel.value.receiveRegion = valueCity.value.join('-')

})
const propsKey = {
    expandTrigger: 'hover',
    value: 'name',
    label: 'name',
    emitPath: true
}
//城市列表
const options: City[] = City
//公开属性 、方法
const props = defineProps<{
    isEdit: boolean
}>()
const emit = defineEmits<{
    (e: 'update:isEdit', isEdit: boolean): void
}>()


// 父组件回显的Expose 方法
const beginAdd = (): void => {
    EditModel.value = {
        id: 0,
        isDefault: 0,
        name: "",
        receiveName: "",
        receiveDetail: "",
        receivePhone: "",
        receiveRegion: ""
    }
    valueCity.value = []
}

const beginUpdate = (data: Vm.Address): void => {
    const modelRegion = data.receiveRegion.split('-')
    valueCity.value = modelRegion
    EditModel.value = { ...data }
}
//父用子方法
defineExpose({
    beginAdd, beginUpdate
})


//增改-保存  删
const save = async (formEl: FormInstance | undefined): Promise<void> => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            console.log('submit!')
            if (EditModel.value.id === 0) Address.addHandler(EditModel.value)
            else Address.editHandler(EditModel.value)
            const loadingInstance = ElLoading.service({ text: "loading..", background: 'rgba(0,0,0,0.5)' })
            await new Promise((resolve: any): void => {
                setTimeout(() => {
                    ElMessage({
                        message: '保存成功！',
                        type: 'success',
                    })
                    resolve()
                    loadingInstance.close()
                }, 500)
            })
            emit('update:isEdit', false)
        } else {
            console.log('error submit!', fields)
            return false
        }
    })


}

const remove = async (id: number) => {
    try {
        await proxy.$miConfirm({ isDefault: true, title: "提示", text: "真的要删除嘛？" })
        await Address.removeHandler(id)
        const loadingInstance = ElLoading.service({ text: "loading..", background: 'rgba(0,0,0,0.5)' })
        await new Promise((resolve: any): void => {
            setTimeout(() => {
                ElMessage({
                    message: '删除成功！',
                    type: 'success',
                })
                resolve()
                loadingInstance.close()
            }, 500)
        })
        emit('update:isEdit', false)
    }
    catch (e) {/**/ }
}








</script>

<style lang="stylus" scoped>
.edit-box
    position fixed
    top 0
    left 0
    bottom 0 
    right 0
    z-index 10
    background-color: rgb(244, 244, 244);
    display flex
    flex-direction column


.header
    height 44px
    display flex
    align-items center
    justify-content center
    position relative
    font-size: 16px;
    flex-shrink 0
.header img
    width 39px
    height 48px
    position absolute
    top 0
    left 0   

.container-box
    background-color #fff
    flex-grow 1
    padding-left: 12px;
    padding-right: 20px
    padding-top 15px


.el-form-item
    border-bottom 1px solid rgb(229,229,229)
    padding-bottom 10px










.footer-eidt
    display flex
    justify-content center
    align-items center
    padding 0 18px
    margin-bottom 9px
    background-color #fff

.footer-eidt button
    color:red
    height: 40px;
    background: linear-gradient(to right, rgb(245, 90, 55), rgb(223, 46, 46));
    border-radius: 20px;
    border 0
    color #fff
    color: rgb(255, 255, 255);
    font-size: 15px;
    font-weight: bold;  
    flex-grow 1

.remove-edit
    color red
    font-size 12px
</style>